package physiqueEngine.thread;

import java.util.Timer;
import java.util.TimerTask;

public abstract class TimeController implements TimeManager
{
    private long period = 0;
    private long tickCount = 0;
    private Timer timer = null;
    
    public TimeController()
    {
        this.tickCount = 0;
    }
    
    @Override
    public long getPeriod()
    {
        return this.period;
    }

    public long getTickCount()
    {
        return this.tickCount;
    }

    @Override
    public boolean isTicking()
    {
        return (this.timer != null);
    }

    @Override
    public boolean setPeriod(long period)
    {
        boolean ok = TimeController.validPeriod(period);
        
        if (ok)
        {
            this.period = period;
        }
        
        return ok;
    }

    @Override
    public void setTicking(boolean ticking)
    {
        if (ticking)
        {
            this.timer = new Timer();
            this.timer.schedule(new TickTask(), 0, this.getPeriod());
        }
        else
        {
            this.timer.cancel();
            this.timer = null;
        }
    }
    
    public abstract void executeTick();
    
    public static boolean validPeriod(long period)
    {
        return (period > 0);
    }

    private class TickTask extends TimerTask
    {
        public void run()
        {
            TimeController.this.executeTick();
            TimeController.this.tickCount++;
        }
    }
}
